package com.example.star.controller;

import com.example.star.entity.Favorite;
import com.example.star.entity.Follow;
import com.example.star.entity.User;
import com.example.star.service.FavoriteService;
import com.example.star.service.FollowService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class FollowController {
    private static final Logger logger = LoggerFactory.getLogger(FollowController.class);

    @Autowired
    private FollowService followService;

    @GetMapping("/follows")
    @ResponseBody
    public List<Follow> getFollows() {
        return followService.getAllFollows();
    }

    @PostMapping("/follows")
    @ResponseBody
    public Follow saveFavorite(@RequestBody Follow follow) {
        followService.saveFollow(follow);
        return follow; // 返回保存的Favorite对象
    }

    @GetMapping("/follows/items-by-user")
    @ResponseBody
    public List<Follow> getFollowByUserName(@RequestParam String userName){
        return followService.getFollowByUserName(userName);
    }

    @DeleteMapping("/follows/{id}")
    public void deleteFollowById(@PathVariable int id) {
        followService.deleteFollowById(id);
    }

    @GetMapping("/follows/{id}")
    public Follow getFollowById(@PathVariable int id) {
        return followService.getFollowById(id);
    }

    @GetMapping("/follows/{starName}")
    public Follow getFollowByStarName(@PathVariable String starName) {
        return followService.getFollowByStarName(starName);
    }

    @GetMapping("/follows/check")
    @ResponseBody
    public boolean checkFollow(@RequestParam String userName, @RequestParam String starName) {
        return followService.isFollow(userName, starName);
    }

    @DeleteMapping("/follows/delete")
    @ResponseBody
    public boolean deleteFollow(@RequestParam String userName, @RequestParam String starName) {
        return followService.deleteFollow(userName, starName);
    }

    @GetMapping("/follow-list")
    public String showFollowList(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "8") int size,
                                 Model model,
                                 HttpServletRequest request) {
        logger.info("接收到的页码: {}", page);
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            // 用户未登录，重定向到登录页面
            return "redirect:/login";
        }
        User user = (User) userObj;
        List<Follow> follows;
        int totalStars;
        try {
            if ("ADMIN".equals(user.getRole())) {
                // 管理员角色，获取所有关注信息
                follows = followService.getFollowsByPage(page, size);
                totalStars = followService.getTotalFollows();
            } else {
                // 普通用户角色，获取该用户的关注信息
                follows = followService.getFollowsByUserName(user.getUsername(), page, size);
                totalStars = followService.getTotalFollowsByUserName(user.getUsername());
            }
            int totalPages = (int) Math.ceil((double) totalStars / size);

            model.addAttribute("follows", follows);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", totalPages);

            return "follow-list";
        } catch (Exception e) {
            logger.error("Error loading follow list", e);
            // 可以在这里返回错误页面或者提示信息
            return "error-page";
        }
    }

    @PostMapping("/follows/{id}")
    public String deleteFollows(@PathVariable int id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        // 从 HttpSession 中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            redirectAttributes.addFlashAttribute("error", "你还未登录，请先登录");
            return "redirect:/login"; // 重定向到登录页面
        }

        User user = (User) userObj;
        // 假设管理员角色名称为 "ADMIN"，根据实际情况修改
        if ("ADMIN".equals(user.getRole())) {
            try {
                followService.deleteFollowById(id);
                redirectAttributes.addFlashAttribute("message", "关注信息删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除关注信息时出现错误：" + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "你没有权限关注收藏信息");
        }
        return "redirect:/follow-list";
    }
}